<template>
  <div class="app-container">
    <!-- 搜索头 -->
    <!-- <transition name="el-zoom-in-top">
      <el-form v-show="searchShow" :inline="true" label-width="80px">
        <el-form-item label="场景名称">
          <el-input v-model="listQuery.title" size="small" />
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            type="primary"
            @click="handleSearchClick"
          >搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            @click="handleSearchCleanClick"
          >清空</el-button>
        </el-form-item>
      </el-form>
    </transition> -->

    <!-- 工具栏 -->
    <div class="tools-container">
      <div class="buttons">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="handleAddClick"
        >新建</el-button>
      </div>
      <!-- <div class="tags">
        <el-button
          size="mini"
          icon="el-icon-search"
          circle
          @click="handleSearchShowChange"
        />
        <el-button
          size="mini"
          icon="el-icon-refresh"
          circle
          @click="handleRefreshClick"
        />
        <el-button
          size="mini"
          icon="el-icon-menu"
          circle
          @click="handleHeaderClick"
        />
      </div> -->
    </div>

    <!-- 表头 -->
    <!-- <el-dialog
      :visible.sync="headerShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="表头"
    >
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >全选</el-checkbox>
      <div style="margin: 15px 0" />
      <el-checkbox-group v-model="header">
        <el-checkbox
          v-for="(value, key) in columns"
          :key="key"
          :label="key"
          :prop="key"
        >{{ value.label }}</el-checkbox>
      </el-checkbox-group>
    </el-dialog> -->

    <!-- 表格 -->
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      class="table-container"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
      stripe
      @sort-change="handleSortChange"
    >
      <el-table-column
        type="index"
        width="50"
        :align="'center'"
        label="序号"
        :width="80"
      />
      <el-table-column
        v-for="(value, key) in columns"
        v-if="value.show"
        :key="key"
        :label="value.label"
        :align="value.center ? 'center' : 'left'"
        :prop="key"
        sortable
      >
        <template slot-scope="scope">
          <!-- <div v-if="value.label === '密码'">
            {{ "******" }}
          </div> -->
          <div v-if="value.label === '角色'">
            <!-- <el-tag
              :type="scope.row.role === 0 ? 'primary' : 'success'"
              disable-transitions
            >{{ scope.row.role === 0 ? "管理员" : "用户" }}</el-tag> -->
            <el-switch
              v-model="scope.row.role"
              active-color="#36c6d3"
              active-text="管理员"
              inactive-text="用户"
              :active-value="0"
              :inactive-value="1"
              @change="active_text(scope.row)"
            />
          </div>
          <div v-else>
            {{ scope.row[key] }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="400">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.role === 1"
            size="mini"
            type="primary"
            plain
            @click="resetPass(scope.row)"
          >重置密码</el-button>
          <el-button
            v-if="scope.row.role === 1"
            size="mini"
            type="warning"
            plain
            @click="resetRule(scope.row)"
          >取消限制</el-button>
          <!-- <el-button
            size="mini"
            type="success"
            plain
            @click="handleEditClick(scope.row)"
          >编辑</el-button> -->
          <el-button
            size="mini"
            type="danger"
            plain
            @click="handleDeleteClick(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表单 -->
    <el-dialog
      :title="isCreate ? '新建记录' : '编辑记录'"
      :visible.sync="formShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleBeforeClose"
    >
      <el-form ref="form" :model="row" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="row.userName" :disabled="!isCreate" />
        </el-form-item>

        <el-form-item label="电话号码">
          <el-input v-model="row.userPhone" :disabled="!isCreate" />
        </el-form-item>
        <el-form-item v-if="!isCreate" label="角色">
          <el-select v-model="row.role" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="电子邮箱">
          <el-input v-model="row.email" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleBeforeClose">取 消</el-button>
        <el-button
          v-if="isCreate"
          type="primary"
          @click="registeredClick"
        >创 建</el-button>
        <el-button
          v-else
          type="primary"
          @click="updateUserClick(2)"
        >更 新</el-button>
      </div>
    </el-dialog>
    <!-- 分页 组件 -->
    <el-pagination
      :current-page.sync="listQuery.pageNum"
      :page-size="listQuery.pageSize"
      :total="total"
      :page-sizes="[5, 10, 20, 30, 50]"
      class="pagination-container"
      background
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 升级 -->
    <el-dialog title="升级版本号" :visible.sync="firmwareShow" width="30%">
      <el-form
        ref="versionForm"
        :model="versionForm"
        label-width="100px"
        :rules="rule"
      >
        <el-form-item label="版本号" prop="fid">
          <el-select v-model="versionForm.fid" placeholder="请选择">
            <el-option
              v-for="item in firmwareList"
              :key="item.id"
              :label="item.version + '/' + item.remark || ''"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="firmwareShow = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleClickUpdate('versionForm')"
        >升 级</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { page, del, update, add, versionUpdate, columns } from '@/api/device'
import {
  users,
  GetUserList,
  updateUser,
  registered,
  deletedUser
} from '@/api/user'
import { maintain } from '@/api/dashboard'
import { getFirmwareList } from '@/api/firmware'
import { toLowerCase } from '@/utils'
import { check } from '@/utils/check'
import { mapGetters } from 'vuex'

export default {
  filters: {
    onlineFilter: function(value) {
      const map = ['在线', '离线']
      return map[value]
    }
  },
  data() {
    return {
      list: [
        {
          user: '张三',
          pass: '123465789',
          role: 0,
          phone: '13122222222',
          email: '12111111@163.com'
        },
        {
          user: '张三',
          pass: '123465789',
          role: 0,
          phone: '13122222222',
          email: '12111111@163.com'
        },
        {
          user: '张三',
          pass: '123465789',
          role: 1,
          phone: '13122222222',
          email: '12111111@163.com'
        },
        {
          user: '张三',
          pass: '123465789',
          role: 1,
          phone: '13122222222',
          email: '12111111@163.com'
        }
      ],
      roleFlag: false,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10
        // order: 'id',
        // title: ''
      },
      total: 0,
      searchShow: false,
      formShow: false,
      isCreate: true, // true创建, false:更新
      headerShow: false,
      isIndeterminate: true,
      checkAll: true,
      columns: [],
      row: {},
      firmwareList: [],
      versionForm: {
        deviceId: '',
        fid: ''
      },
      rule: {
        fid: [{ required: true, message: '请选择版本', trigger: 'change' }]
      },
      firmwareShow: false,
      checkAdd: false,
      checkEdit: false,
      checkDelete: false,
      options: [
        {
          value: 0,
          label: '管理员'
        },
        {
          value: 1,
          label: '用户'
        }
      ]
    }
  },
  computed: {
    // ...mapGetters([
    //   'roles'
    // ]),
    rowSwitch(role) {
      return role === 0
    },
    header: {
      set: function(v) {
        Object.keys(this.columns).forEach((key) => {
          this.columns[key].show = false
          v.forEach((i) => {
            if (key === i) {
              this.columns[key].show = true
            }
          })
        })
        const checkedCount = v.length
        this.checkAll = checkedCount === Object.keys(this.columns).length
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < Object.keys(this.columns).length
        return Object.keys(this.columns).filter((i) => this.columns[i].show)
      },
      get: function() {
        var array = Object.keys(this.columns).filter(
          (i) => this.columns[i].show
        )
        return array
      }
    }
  },
  mounted() {
    // check(this.roles, ['激活设备', '编辑设备', '删除设备'], (list) => {
    //   this.checkAdd = list[0]
    //   this.checkEdit = list[1]
    //   this.checkDelete = list[2]
    // })
    // this.fetchData()
    this.GetUserList()
    this.columns = users()
    var checkedCount = this.header.length
    this.checkAll = checkedCount === Object.keys(this.columns).length
    this.isIndeterminate =
      checkedCount > 0 && checkedCount < Object.keys(this.columns).length
  },
  methods: {
    // 修改管理员
    active_text(row) {
      updateUser({
        phone: row.userPhone,
        role: row.role,
        type: 2
      }).then((res) => {
        this.GetUserList()
        this.$message({
          message: res.msg,
          type: 'success',
          duration: 800
        })
      })
    },
    // 查询
    GetUserList() {
      GetUserList(this.listQuery).then((res) => {
        if (res.status === 200) {
          this.list = res.data.pageList
          this.total = res.data.total
          this.listLoading = false
        }
      })
    },
    // 修改
    updateUserClick(type) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.row.type = type
          updateUser({
            phone: this.row.userPhone,
            role: this.row.role,
            type: this.row.type
          }).then((res) => {
            this.GetUserList()
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 800
            })
            this.formShow = false
            this.form = {}
          })
        }
      })
    },
    fetchData() {
      this.listLoading = true
      page(this.listQuery).then((response) => {
        this.list = response.data.records.map((item) => {
          const ccidData = item.ccidData
            ? item.ccidData === 'Error request, response status: 405'
              ? ''
              : JSON.parse(item.ccidData)
            : ''
          return {
            ...item,
            ll: ccidData
              ? ccidData.status === '0'
                ? `${ccidData.data.left_flow} || ${ccidData.data.total_flow}`
                : ''
              : ''
          }
        })
        this.total = response.data.total
        this.listLoading = false
      })
    },

    // <<<< 搜索头
    // handleSearchClick() {
    //   if (!this.listQuery.title) {
    //     this.$message({
    //       message: '搜索内容不能为空',
    //       type: 'error',
    //       duration: 800
    //     })
    //   }
    // },
    // handleSearchCleanClick() {
    //   this.listQuery.title = ''
    // },
    // >>>> 搜索头

    // <<<< 工具栏相关
    // handleCheckAllChange(val) {
    //   this.header = val ? Object.keys(this.columns) : []
    //   Object.keys(this.columns).forEach((key) => {
    //     this.columns[key].show = val
    //   })
    //   this.isIndeterminate = false
    // },
    handleRefreshClick() {
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 800
      })
      this.GetUserList()
    },
    handleSearchShowChange() {
      this.searchShow = !this.searchShow
    },
    handleAddClick() {
      this.isCreate = true
      this.formShow = true
      this.row = {
        deflectionX: 0,
        deflectionY: 0,
        deflectionZ: 0
      }
    },
    // 升级版本
    handleUpdate(data) {
      getFirmwareList({ deviceId: data.id }).then((res) => {
        if (res.ok) {
          this.firmwareList = res.data
        }
      })
      this.versionForm = {
        deviceId: data.id,
        fid: data.fid
      }
      this.firmwareShow = true
    },
    handleClickUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const { deviceId, fid } = this.versionForm
          versionUpdate({
            deviceId,
            fid
          }).then((res) => {
            if (res.ok) {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 800
              })
              this.firmwareShow = false
              this.GetUserList()
            }
          })
        }
      })
    },
    // 维护模式的开启与关闭 1 关闭状态 0 开启状态
    clickMaintain(data) {
      maintain({
        deviceId: data.id,
        status: data.isMain ? 0 : 1
      }).then((res) => {
        if (res.ok) {
          this.$message({
            type: 'success',
            message: res.data
          })
          this.GetUserList()
        }
      })
    },
    // >>>> 工具栏相关

    // <<<< 表头相关

    // >>>> 表头相关

    // <<<< 表格相关
    handleDeleteClick(row) {
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deletedUser({ id: row.id }).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 800
            })
            this.GetUserList()
          })
        })
        .catch(() => {
          console.log('取消删除')
        })
    },
    handleEditClick(row) {
      this.isCreate = false
      this.formShow = true
      this.row = Object.assign({}, row)
    },
    handleBeforeClose() {
      this.row = {}
      this.formShow = false
      this.$refs.form.resetFields()
    },
    // >>>> 表格相关

    // <<<< 分页相关
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.GetUserList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.GetUserList()
    },
    handleSortChange(val) {
      this.listQuery.asc = val.order !== 'descending'
      this.listQuery.order = toLowerCase(val.prop)
      this.GetUserList()
    },
    handleHeaderClick() {
      this.headerShow = true
    },
    // >>>> 分页相关
    registeredClick() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          registered({
            userName: this.row.userName,
            userPhone: this.row.userPhone
          }).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 800
            })
            this.GetUserList()
            this.formShow = false
            this.form = {}
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    normalApi(row, type) {
      this.$confirm('此操作将修改用户状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          updateUser({
            type: type,
            phone: row.userPhone
          }).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 800
            })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    resetPass(row) {
      this.normalApi(row, 1)
    },
    resetRule(row) {
      this.normalApi(row, 2)
    }
    // <<<< 表单相关
    // handleCreateClick() {
    //   this.$refs.form.validate((valid) => {
    //     if (valid) {
    //       this.row.x = this.row.x ? this.row.x : 0
    //       this.row.y = this.row.y ? this.row.y : 0
    //       this.row.z = this.row.z ? this.row.z : 0
    //       add(this.row).then((res) => {
    //         this.$message({
    //           message: res.data,
    //           type: 'success',
    //           duration: 800
    //         })
    //         this.GetUserList()
    //         this.formShow = false
    //         this.form = {}
    //       })
    //     } else {
    //       console.log('error submit!!')
    //       return false
    //     }
    //   })
    // },
    // handleUpdateClick() {
    //   this.$refs.form.validate((valid) => {
    //     if (valid) {
    //       update(this.row).then((res) => {
    //         this.GetUserList()
    //         this.$message({
    //           message: res.msg,
    //           type: 'success',
    //           duration: 800
    //         })
    //         this.formShow = false
    //         this.form = {}
    //       })
    //     }
    //   })
    // }
    // >>>> 表单相关

    // <<<<<script 其他业务
    // >>>>> 其他业务
  }
}
</script>
